package com.jtlrm.ckd.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.base.sdk.base.net.CommonObserver;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.PageEntity;
import com.jtlrm.ckd.entity.SuiFangPaiBanEntity;
import com.jtlrm.ckd.entity.event.SuiFangUpdateMessage;
import com.jtlrm.ckd.mvp.model.SuiFangPaiBanModel;
import com.jtlrm.ckd.mvp.view.adapter.AddSuiFangAdapter;
import com.jtlrm.ckd.util.EventBusUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.util.List;

import butterknife.BindView;

public class AddSuiFangPersonActivity extends TitleBarActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    AddSuiFangAdapter adapter;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private int pageNum = 1;
    private int pageSize = 12;
    private String suiFangTime;
    SuiFangPaiBanModel paiBanModel;
    @BindView(R.id.check_all)
    CheckBox selectAllC;
    @BindView(R.id.info)
    TextView basicInfo;
    @BindView(R.id.select_num)
    TextView selectNumT;

    public static void goAdd(Context context, String addTime) {
        Intent intent = new Intent(context, AddSuiFangPersonActivity.class);
        intent.putExtra("addTime", addTime);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        suiFangTime = getIntent().getStringExtra("addTime");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTitleText() {
        return "选择随访患者";
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_add_sui_fang_person);
    }

    @Override
    protected void initView() {
        paiBanModel = new SuiFangPaiBanModel();
        adapter = new AddSuiFangAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(createItemDecoration());
        recyclerView.setAdapter(adapter);
        String info = "您将要选择这些患者到" + suiFangTime + "随访";
        SpannableString spannableString = new SpannableString(info);
        //设置颜色
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#F7A98B")), info.indexOf("到") + 1, info.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        basicInfo.setText(spannableString);
    }

    @Override
    protected void obtainData() {
    }

    @Override
    protected void initEvent() {
        adapter.openLoadAnimation();
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNum++;
                loadData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                loadData();
            }
        });
        smartRefreshLayout.autoRefresh();
        selectAllC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectAllC.isChecked()) {
                    selectAll(true);
                } else {
                    selectAll(false);
                }
            }
        });
        adapter.setUpdateSelect(new AddSuiFangAdapter.UpdateSelect() {
            @Override
            public void update() {
                updateSelectNum();
            }
        });
    }

    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        titleBar.tvRight.setText("确定");
        titleBar.tvRight.setVisibility(View.VISIBLE);
        titleBar.tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
    }

    private void submit() {
        List<SuiFangPaiBanEntity> data = adapter.getData();
        if (data == null || data.size() == 0) {
            showToast("数据为空，不能提交");
            return;
        }
        String selectId = "";
        for (SuiFangPaiBanEntity entity : data) {
            if (entity.isSelect()) {
                if (notEmpty(selectId)) {
                    selectId = selectId + "," + entity.getId();
                } else {
                    selectId = entity.getId();
                }
            }
        }
        if (!notEmpty(selectId)) {
            showToast("至少选择一人才能提交");
            return;
        }
        showLoadingDialog("提交中");
        paiBanModel.addSuiFang(suiFangTime, selectId, new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(String data) {
                showToast("提交成功");
                dismissLoadingDialog();
                EventBusUtil.postEvent(new SuiFangUpdateMessage());
                finish();
            }
        }, lifecycleSubject);
    }

    /**
     * 是否全部选中
     *
     * @param isSelectAll
     */
    private void selectAll(boolean isSelectAll) {
        List<SuiFangPaiBanEntity> data = adapter.getData();
        if (data == null || data.size() == 0) {
            return;
        }
        if (isSelectAll) {
            for (SuiFangPaiBanEntity entity : data) {
                entity.setSelect(true);
            }
        } else {
            for (SuiFangPaiBanEntity entity : data) {
                entity.setSelect(false);
            }
        }
        adapter.notifyDataSetChanged();
        updateSelectNum();
    }

    private void loadData() {
        paiBanModel.queryAddSuiFangList(suiFangTime, pageNum, pageSize, new CommonObserver<PageEntity<List<SuiFangPaiBanEntity>>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                closeFrshorLoadmore();
            }

            @Override
            public void onResult(PageEntity<List<SuiFangPaiBanEntity>> data) {
                selectAllC.setChecked(false);
                if (pageNum == 1) {
                    adapter.replaceData(data.getItems());
                } else {
                    adapter.addData(data.getItems());
                }
                if (data.getItems().size() < pageSize) {
                    smartRefreshLayout.setEnableLoadmore(false);
                } else {
                    smartRefreshLayout.setEnableLoadmore(true);
                }
                updateSelectNum();
                closeFrshorLoadmore();
            }
        }, lifecycleSubject);
    }


    /**
     * 更新选中人数
     */
    private void updateSelectNum() {
        List<SuiFangPaiBanEntity> data = adapter.getData();
        if (data == null || data.size() == 0) {
            setText(selectNumT, "共0人");
            return;
        }
        int num = 0;
        for (SuiFangPaiBanEntity entity : data) {
            if (entity.isSelect()) {
                ++num;
            }
        }
        setText(selectNumT, "共" + num + "人");
    }


    /**
     * 关闭加载更多或者刷新
     */
    private void closeFrshorLoadmore() {
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
    }

    protected RecyclerView.ItemDecoration createItemDecoration() {
        return new DefaultItemDecoration(ContextCompat.getColor(this, R.color.margin_background), 2, 20, -1);
    }
}
